function hasChild (item) {
    return item.children && item.children.length !== 0;
};

export const getMenuByRouter = (routes) => {
    let res = [];

    routes.forEach(item => {
        if (item.meta) {
            let obj = {
                label: item.meta.title,
                name: item.name
            };
            if (hasChild(item)) {
                obj.children = getMenuByRouter(item.children);
            }
            res.push(obj);
        }
    });

    return res;
};

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
    let res = [];
    let temp = {};
    for (let i = 0; i < data.length; i++) {
        temp[data[i][id]] = data[i];
    }
    for (let k = 0; k < data.length; k++) {
        if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
            if (!temp[data[k][pid]]['children']) {
                temp[data[k][pid]]['children'] = [];
            }
            if (!temp[data[k][pid]]['_level']) {
                temp[data[k][pid]]['_level'] = 1;
            }
            data[k]['_level'] = temp[data[k][pid]]._level + 1;
            temp[data[k][pid]]['children'].push(data[k]);
        } else {
            res.push(data[k]);
        }
    }
    return res;
}

/**
 *
 * @date 2018/4/9
 * @Description: 时间格式化 使用方式parseTime('{y}-{m}-{d} {h}:{i}:{s}')
 *
 */
export function parseTime (time, cFormat) {
    if (arguments.length === 0) {
        return null;
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if (('' + time).length === 10) { time = parseInt(time) * 1000; }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        if (key === 'a') { return ['一', '二', '三', '四', '五', '六', '日'][value - 1]; }
        if (result.length > 0 && value < 10) {
            value = '0' + value;
        }
        return value || 0;
    });
    return time_str;
}

/**
 * @author KdZhao/dongwenzhao@lngtop.com
 * @date 2019-01-04 14:10:27
 * @Description: 节流函数
 */
export function throttle (fn, interval) {
    var __self = fn; // 保存需要被延迟执行的函数引用
    var timer; // 定时器
    var firstTime = true; // 是否是第一次调用
    return function () {
        var args = arguments;
        var __me = this;
        if (firstTime) { // 如果是第一次调用，不需延迟执行
            __self.apply(__me, args);
            firstTime = false;
            return firstTime;
        }
        if (timer) { // 如果定时器还在，说明前一次延迟执行还没有完成
            return false;
        }
        timer = setTimeout(function () { // 延迟一段时间执行
            clearTimeout(timer);
            timer = null;
            __self.apply(__me, args);
        }, interval || 500);
    };
};

/**
 * @author KdZhao/dongwenzhao@lngtop.com
 * @date 2019-04-18 15:03:26
 * @Description: 防抖函数
 */

export function debounce (func, wait, immediate) {
    let timeout, args, context, timestamp, result;

    const later = function () {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp;

        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last);
        } else {
            timeout = null;
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args);
                if (!timeout) { context = args = null; }
            }
        }
    };

    return function (...args) {
        context = this;
        timestamp = +new Date();
        const callNow = immediate && !timeout;
        // 如果延时不存在，重新设定延时
        if (!timeout) { timeout = setTimeout(later, wait); }
        if (callNow) {
            result = func.apply(context, args);
            context = args = null;
        }

        return result;
    };
}

/**
 * @description yesterday 昨天 oneMonth 最近一个月 threeMonth 最近三个月
 * @returns {Object} 开始时间，结束时间
 */
export const timeInterval = {
    Time: function (now, h = false) {
        let year = new Date(now).getFullYear();
        let month = new Date(now).getMonth() + 1;
        let date = new Date(now).getDate();
        if (month < 10) { month = '0' + month; }
        if (date < 10) { date = '0' + date; }
        if (h) {
            let hours = new Date(now).getHours();
            let minutes = new Date(now).getMinutes();
            let seconds = new Date(now).getSeconds();
            return `${year}/${month}/${date} ${hours}:${minutes}:${seconds}`;
        }
        return year + '/' + month + '/' + date;
    },
    getMonthDays: function (myMonth) {
        let monthStartDate = new Date(new Date().getFullYear(), myMonth, 1);
        let monthEndDate = new Date(new Date().getFullYear(), myMonth + 1, 1);
        let days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
        return days;
    },
    today: function () {
        let startTime = this.Time(new Date().getTime() - 24 * 60 * 60 * 1000, true);
        let endTime = this.Time(new Date().getTime(), true);
        return {startTime, endTime};
    },
    yesterday: function () {
        let startTime = this.Time(new Date().getTime() - 24 * 60 * 60 * 1000) + ' 00:00:00';
        let endTime = this.Time(new Date().getTime() - 24 * 60 * 60 * 1000) + ' 23:59:59';
        return {startTime, endTime};
    },
    sevenDay: function () {
        let endTime = this.Time(new Date().getTime()) + ' 23:59:59';
        let startTime = this.Time(new Date().getTime() - 6 * 24 * 60 * 60 * 1000) + ' 00:00:00';
        return {startTime, endTime};
    },
    nearOneMonth: function () {
        let startTime = this.Time(new Date(new Date().getFullYear(), new Date().getMonth(), 1)) + ' 00:00:00';
        let endTime = this.Time(new Date().getTime()) + ' 23:59:59';
        return {startTime, endTime};
    },
    oneMonth: function () {
        let startTime = this.Time(new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1)) + ' 00:00:00';
        let endTime = this.Time(new Date(new Date().getFullYear(), new Date().getMonth() - 1, this.getMonthDays(new Date().getMonth() - 1))) + ' 23:59:59';
        return {startTime, endTime};
    },
    threeMonth: function () {
        let startTime = this.Time(new Date(new Date().getFullYear(), new Date().getMonth() - 3, 1)) + ' 00:00:00';
        let endTime = this.Time(new Date(new Date().getFullYear(), new Date().getMonth() - 1, this.getMonthDays(new Date().getMonth() - 3))) + ' 23:59:59';
        return {startTime, endTime};
    },
    halfYear: function () {
        let startTime = this.Time(new Date(new Date().getFullYear(), new Date().getMonth() - 6, 1)) + ' 00:00:00';
        let endTime = this.Time(new Date(new Date().getFullYear(), new Date().getMonth() - 1, this.getMonthDays(new Date().getMonth() - 1))) + ' 23:59:59';
        return {startTime, endTime};
    },
    oneYear: function () {
        let startTime = this.Time(new Date(new Date().getFullYear(), new Date().getMonth() - 12, 1)) + ' 00:00:00';
        let endTime = this.Time(new Date(new Date().getFullYear(), new Date().getMonth() - 1, this.getMonthDays(new Date().getMonth() - 1))) + ' 23:59:59';
        return {startTime, endTime};
    }

};
